package com.videoweb.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.videoweb.entity.User;
import com.videoweb.entity.Role;
import com.videoweb.entity.dto.UserInfoDTO;
import com.videoweb.service.IUserService;
import com.videoweb.service.IRoleService;
import com.videoweb.utils.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lmr
 * @since 2025-05-17
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;
    @Autowired
    private IRoleService roleService;


    @GetMapping("/info/{id}")
    public AjaxResult getUserInfoByUserId(@PathVariable("id") Long userId) {

        AjaxResult result = AjaxResult.success();
        UserInfoDTO userInfoDTO = userService.getBaseUserInfo(userId);

        return result.put("userInfo", userInfoDTO);
    }


    // 用户列表（分页+条件）
    @GetMapping("/list")
    public AjaxResult list(@RequestParam Map<String, Object> params) {
        int pageNum = params.get("pageNum") != null ? Integer.parseInt(params.get("pageNum").toString()) : 1;
        int pageSize = params.get("pageSize") != null ? Integer.parseInt(params.get("pageSize").toString()) : 10;
        Page<User> page = new Page<>(pageNum, pageSize);
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        if (params.get("username") != null) {
            wrapper.like("username", params.get("username"));
        }
        if (params.get("nickname") != null) {
            wrapper.like("nickname", params.get("nickname"));
        }
        if (params.get("phone") != null) {
            wrapper.like("phone", params.get("phone"));
        }
        if (params.get("status") != null) {
            wrapper.eq("status", params.get("status"));
        }
        Page<User> userPage = userService.page(page, wrapper);
        return AjaxResult.success(userPage);
    }

    // 查询单个用户
    @GetMapping("/{id}")
    public AjaxResult getUser(@PathVariable Long id) {
        User user = userService.getById(id);
        return AjaxResult.success(user);
    }

    // 新增用户
    @PostMapping
    public AjaxResult addUser(@RequestBody User user) {
        boolean ok = userService.addUser(user);
        return ok ? AjaxResult.success("添加成功") : AjaxResult.error("添加失败");
    }

    // 修改用户
    @PutMapping
    public AjaxResult updateUser(@RequestBody User user) {
        boolean ok = userService.updateById(user);
        return ok ? AjaxResult.success("修改成功") : AjaxResult.error("修改失败");
    }

    // 删除用户
    @DeleteMapping("/{id}")
    public AjaxResult deleteUser(@PathVariable Long id) {
        boolean ok = userService.removeById(id);
        return ok ? AjaxResult.success("删除成功") : AjaxResult.error("删除失败");
    }

    // 查询所有角色
    @GetMapping("/roleList")
    public AjaxResult getRoleList() {
        List<Role> roles = roleService.list();
        return AjaxResult.success(roles);
    }

    // 查询用户已分配角色
    @GetMapping("/roles/{userId}")
    public AjaxResult getUserRoles(@PathVariable Long userId) {
        List<Long> roleIds = userService.getRoleIdsByUserId(userId);
        return AjaxResult.success(roleIds);
    }

    // 分配角色
    @PostMapping("/assignRole")
    public AjaxResult assignRole(@RequestBody Map<String, Object> data) {
        Long userId = Long.valueOf(data.get("userId").toString());
        List<?> roleIdsRaw = (List<?>) data.get("roleIds");
        List<Integer> roleIds = new java.util.ArrayList<>();
        for (Object obj : roleIdsRaw) {
            roleIds.add(Integer.valueOf(obj.toString()));
        }
        boolean ok = userService.assignRoles(userId, roleIds);
        return ok ? AjaxResult.success("分配成功") : AjaxResult.error("分配失败");
    }

    // 取消角色
    @PostMapping("/removeRole")
    public AjaxResult removeRole(@RequestBody Map<String, Object> data) {
        Long userId = Long.valueOf(data.get("userId").toString());
        Long roleId = Long.valueOf(data.get("roleId").toString());
        boolean ok = userService.removeRole(userId, roleId);
        return ok ? AjaxResult.success("取消成功") : AjaxResult.error("取消失败");
    }
}
